package controllers

import (
	"net/http"

	"WHY_GIN/service"

	"github.com/gin-gonic/gin"
)

// TakeProfitController 止盈控制器
type TakeProfitController struct{}

// NewTakeProfitController 创建新的止盈控制器
func NewTakeProfitController() *TakeProfitController {
	return &TakeProfitController{}
}

// StartTakeProfitRequest 启动止盈请求参数
type StartTakeProfitRequest struct {
	Symbol            string  `json:"symbol" binding:"required"`            // 交易对（必填）
	ResistancePrice   float64 `json:"resistance_price" binding:"required"`   // 压力位价格（必填）
	BasePositionRate  float64 `json:"base_position_rate"`                    // 底仓保留比例（默认0.2即20%）
	FirstSellRate     float64 `json:"first_sell_rate"`                       // 首次卖出比例（默认0.3即30%）
	SecondSellTrigger float64 `json:"second_sell_trigger"`                   // 二次卖出触发涨幅（默认0.1即10%）
}

// StartTakeProfitMonitoring 启动止盈监控
// @Summary 启动止盈监控
// @Description 启动止盈策略监控，可配置底仓保留比例、首次卖出比例和二次卖出触发涨幅
// @Tags 止盈管理
// @Accept json
// @Produce json
// @Param request body StartTakeProfitRequest false "启动参数（base_position_rate: 底仓保留比例, first_sell_rate: 首次卖出比例, second_sell_trigger: 二次卖出触发涨幅）"
// @Success 200 {object} map[string]interface{} "启动成功"
// @Failure 400 {object} map[string]interface{} "启动失败"
// @Router /api/take-profit/start [post]
func (tpc *TakeProfitController) StartTakeProfitMonitoring(c *gin.Context) {
	// 解析请求参数
	var req StartTakeProfitRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "参数解析失败",
			"error":   "交易对(symbol)和压力位价格(resistance_price)为必填参数",
		})
		return
	}

	// 验证必填参数
	if req.Symbol == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "参数验证失败",
			"error":   "交易对(symbol)不能为空",
		})
		return
	}

	if req.ResistancePrice <= 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "参数验证失败",
			"error":   "压力位价格(resistance_price)必须大于0",
		})
		return
	}

	// 设置默认参数
	if req.BasePositionRate <= 0 || req.BasePositionRate >= 1 {
		req.BasePositionRate = 0.20  // 默认保留20%底仓
	}
	if req.FirstSellRate <= 0 || req.FirstSellRate >= 1 {
		req.FirstSellRate = 0.30     // 默认首次卖出30%
	}
	if req.SecondSellTrigger <= 0 || req.SecondSellTrigger > 1 {
		req.SecondSellTrigger = 0.10 // 默认上涨10%触发二次卖出
	}

	// 验证参数逻辑合理性
	if req.BasePositionRate+req.FirstSellRate >= 1 {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "参数配置错误",
			"error":   "底仓保留比例 + 首次卖出比例不能大于等于100%",
		})
		return
	}

	// 设置压力位
	err := service.SetResistanceLevelForSymbol(req.Symbol, req.ResistancePrice)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "设置压力位失败",
			"error":   err.Error(),
		})
		return
	}

	// 设置策略参数
	err = service.SetTakeProfitStrategyParams(req.BasePositionRate, req.FirstSellRate, req.SecondSellTrigger)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "设置策略参数失败",
			"error":   err.Error(),
		})
		return
	}

	// 启动止盈监控
	err = service.StartTakeProfitMonitoring()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "启动止盈监控失败",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "止盈策略启动成功",
		"data": gin.H{
			"symbol":              req.Symbol,
			"resistance_price":    req.ResistancePrice,
			"base_position_rate":  req.BasePositionRate,
			"first_sell_rate":     req.FirstSellRate,
			"second_sell_trigger": req.SecondSellTrigger,
		},
	})
}

// StopTakeProfitMonitoring 停止止盈监控
// @Summary 停止止盈监控
// @Description 停止止盈策略监控
// @Tags 止盈管理
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "停止成功"
// @Failure 400 {object} map[string]interface{} "停止失败"
// @Router /api/take-profit/stop [post]
func (tpc *TakeProfitController) StopTakeProfitMonitoring(c *gin.Context) {
	err := service.StopTakeProfitMonitoring()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "停止止盈监控失败",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "止盈监控已停止",
		"data":    service.GetTakeProfitStatus(),
	})
}

// GetTakeProfitStatus 获取止盈状态
// @Summary 获取止盈状态
// @Description 获取止盈策略的当前运行状态和配置信息
// @Tags 止盈管理
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "状态信息"
// @Router /api/take-profit/status [get]
func (tpc *TakeProfitController) GetTakeProfitStatus(c *gin.Context) {
	status := service.GetTakeProfitStatus()

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "获取止盈状态成功",
		"data":    status,
	})
}

// SetResistanceLevelRequest 设置压力位请求参数
type SetResistanceLevelRequest struct {
	Symbol string  `json:"symbol" binding:"required"` // 交易对
	Price  float64 `json:"price" binding:"required"`  // 压力位价格
}

// SetResistanceLevel 设置压力位
// @Summary 设置压力位
// @Description 为指定交易对设置压力位价格，用于触发止盈策略
// @Tags 止盈管理
// @Accept json
// @Produce json
// @Param request body SetResistanceLevelRequest true "压力位设置参数"
// @Success 200 {object} map[string]interface{} "设置成功"
// @Failure 400 {object} map[string]interface{} "设置失败"
// @Router /api/take-profit/resistance-level [post]
func (tpc *TakeProfitController) SetResistanceLevel(c *gin.Context) {
	var req SetResistanceLevelRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "参数错误",
			"error":   err.Error(),
		})
		return
	}

	// 参数验证
	if req.Price <= 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "价格参数错误",
			"error":   "压力位价格必须大于0",
		})
		return
	}

	// 设置压力位
	err := service.SetResistanceLevelForSymbol(req.Symbol, req.Price)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "设置压力位失败",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "压力位设置成功",
		"data": gin.H{
			"symbol": req.Symbol,
			"price":  req.Price,
		},
	})
}

// RemoveResistanceLevel 移除压力位
// @Summary 移除压力位
// @Description 移除指定交易对的压力位设置
// @Tags 止盈管理
// @Accept json
// @Produce json
// @Param symbol path string true "交易对符号"
// @Success 200 {object} map[string]interface{} "移除成功"
// @Failure 400 {object} map[string]interface{} "移除失败"
// @Router /api/take-profit/resistance-level/{symbol} [delete]
func (tpc *TakeProfitController) RemoveResistanceLevel(c *gin.Context) {
	symbol := c.Param("symbol")
	if symbol == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "参数错误",
			"error":   "交易对符号不能为空",
		})
		return
	}

	// 移除压力位
	err := service.RemoveResistanceLevelForSymbol(symbol)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "移除压力位失败",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "压力位移除成功",
		"data": gin.H{
			"symbol": symbol,
		},
	})
}

// GetResistanceLevel 获取压力位
// @Summary 获取压力位
// @Description 获取指定交易对的压力位价格
// @Tags 止盈管理
// @Accept json
// @Produce json
// @Param symbol path string true "交易对符号"
// @Success 200 {object} map[string]interface{} "获取成功"
// @Failure 400 {object} map[string]interface{} "获取失败"
// @Router /api/take-profit/resistance-level/{symbol} [get]
func (tpc *TakeProfitController) GetResistanceLevel(c *gin.Context) {
	symbol := c.Param("symbol")
	if symbol == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "参数错误",
			"error":   "交易对符号不能为空",
		})
		return
	}

	// 获取压力位
	if service.GlobalTakeProfitManager == nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "止盈管理器未初始化",
		})
		return
	}

	price, exists := service.GlobalTakeProfitManager.GetResistanceLevel(symbol)
	if !exists {
		c.JSON(http.StatusNotFound, gin.H{
			"success": false,
			"message": "压力位不存在",
			"error":   "指定交易对未设置压力位",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "获取压力位成功",
		"data": gin.H{
			"symbol": symbol,
			"price":  price,
		},
	})
}

// GetAllResistanceLevels 获取所有压力位
// @Summary 获取所有压力位
// @Description 获取所有已设置的压力位信息
// @Tags 止盈管理
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "获取成功"
// @Router /api/take-profit/resistance-levels [get]
func (tpc *TakeProfitController) GetAllResistanceLevels(c *gin.Context) {
	if service.GlobalTakeProfitManager == nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "止盈管理器未初始化",
		})
		return
	}

	resistanceLevels := service.GlobalTakeProfitManager.GetAllResistanceLevels()

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "获取所有压力位成功",
		"data": gin.H{
			"resistance_levels": resistanceLevels,
			"count":             len(resistanceLevels),
		},
	})
}

// UpdateStrategyParamsRequest 更新策略参数请求
type UpdateStrategyParamsRequest struct {
	BasePositionRate  *float64 `json:"base_position_rate,omitempty"`  // 底仓保留比例
	FirstSellRate     *float64 `json:"first_sell_rate,omitempty"`     // 首次卖出比例
	SecondSellTrigger *float64 `json:"second_sell_trigger,omitempty"` // 二次卖出触发涨幅
}

// UpdateStrategyParams 更新策略参数
// @Summary 更新策略参数
// @Description 更新止盈策略的参数配置
// @Tags 止盈管理
// @Accept json
// @Produce json
// @Param request body UpdateStrategyParamsRequest true "策略参数更新"
// @Success 200 {object} map[string]interface{} "更新成功"
// @Failure 400 {object} map[string]interface{} "更新失败"
// @Router /api/take-profit/strategy-params [put]
func (tpc *TakeProfitController) UpdateStrategyParams(c *gin.Context) {
	var req UpdateStrategyParamsRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "参数错误",
			"error":   err.Error(),
		})
		return
	}

	if service.GlobalTakeProfitManager == nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "止盈管理器未初始化",
		})
		return
	}

	// 获取当前状态
	status := service.GetTakeProfitStatus()
	currentBaseRate := status["base_position_rate"].(float64)
	currentFirstRate := status["first_sell_rate"].(float64)
	currentSecondTrigger := status["second_sell_trigger"].(float64)

	// 使用新值或保持当前值
	newBaseRate := currentBaseRate
	newFirstRate := currentFirstRate
	newSecondTrigger := currentSecondTrigger

	if req.BasePositionRate != nil {
		if *req.BasePositionRate <= 0 || *req.BasePositionRate >= 1 {
			c.JSON(http.StatusBadRequest, gin.H{
				"success": false,
				"message": "底仓保留比例参数错误",
				"error":   "底仓保留比例必须在0-1之间",
			})
			return
		}
		newBaseRate = *req.BasePositionRate
	}

	if req.FirstSellRate != nil {
		if *req.FirstSellRate <= 0 || *req.FirstSellRate >= 1 {
			c.JSON(http.StatusBadRequest, gin.H{
				"success": false,
				"message": "首次卖出比例参数错误",
				"error":   "首次卖出比例必须在0-1之间",
			})
			return
		}
		newFirstRate = *req.FirstSellRate
	}

	if req.SecondSellTrigger != nil {
		if *req.SecondSellTrigger <= 0 || *req.SecondSellTrigger > 1 {
			c.JSON(http.StatusBadRequest, gin.H{
				"success": false,
				"message": "二次卖出触发涨幅参数错误",
				"error":   "二次卖出触发涨幅必须在0-1之间",
			})
			return
		}
		newSecondTrigger = *req.SecondSellTrigger
	}

	// 验证参数逻辑合理性
	if newBaseRate+newFirstRate >= 1 {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "参数配置错误",
			"error":   "底仓保留比例 + 首次卖出比例不能大于等于100%",
		})
		return
	}

	// 更新策略参数
	err := service.SetTakeProfitStrategyParams(newBaseRate, newFirstRate, newSecondTrigger)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "更新策略参数失败",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "策略参数更新成功",
		"data":    service.GetTakeProfitStatus(),
	})
}
